﻿using W.Models.DataAccess;
using System.Collections.Generic;
using System.Data;
using System;
using System.Reflection;
using System.Linq;
using System.Data.Objects;
using System.Data.Linq;
using W.Models.Utils;

namespace W.Component
{
    public class ComponentBase<TEntity> where TEntity : class
    {
        protected DataModel Model = new DataModel();
        private string TName = typeof(TEntity).Name;

        public ComponentBase() { }

        public virtual void Create(TEntity Entity)
        {
            Model.AddObject(TName, Entity);
            Model.SaveChanges();
        }

        public virtual void Delete(int id)
        {
            this.Model.DeleteObject(Get(id));
            this.Model.SaveChanges();
        }

        public virtual TEntity Get(int id)
        {
            ObjectSet<TEntity> Property = (ObjectSet<TEntity>)Model.GetType().GetProperty(TName).GetValue(Model, null);

            Property.IncludeAll();

            TEntity Entity = Property.SingleOrDefault(delegate(dynamic t)
            {
                return t.id == id;
            });

            return Entity;
        }

        protected T Get<T>(int id) where T : class
        {
            ObjectSet<T> Property = (ObjectSet<T>)Model.GetType().GetProperty(typeof(T).Name).GetValue(Model, null);

            Property.IncludeAll();

            return Property.SingleOrDefault(delegate(dynamic t)
            {
                return t.id == id;
            });
        }

        public virtual void Update(TEntity Entity)
        {
            Model.AttachTo(TName, Entity);
            Model.ObjectStateManager.ChangeObjectState(Entity, EntityState.Modified);
            Model.SaveChanges();
        }
    }
}